// pages/select/index.js
const { fetchClassList, fetchEnter } = require('../../services/index')
const { notice } = require('../../services/setting')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    dateUI: [],
    dateH5: [],
    height:'',
    isActive:"course",
    edu: ['大专', '本科', '其它'],
    student:{
      name: '', // 姓名
      sex: 1,  // 1男 2女
      phone: '', // 电话
      class_id: '', // 班级id,
      class_name: '', // 班级名称,
      wx_openid: '',
      wx_nickname: '',
      wx_avatar: '',
      provice: '省', // 省
      city: '市', //  市
      county: '区', // 县
      now_status: 1, // 1:应届，2：在校，3：转行,
      pre_career: '', // 前职业
      school: '', // 学校
      major: '', // 专业
      education: '', // 学历
      is_base: 1, // 是否有基础:1:有,2:没有
      other_name: '', // 紧急联系人
      other_phone: '', // 紧急联系人电话
      other_relation: '', // 紧急联系人关系
      remarks: '', // 备注

      type: undefined, // 班级类型 1:ui， 2前端
      isAgree:false
    },
    notice,
    rules:[
      {
        name: 'type',
        rules: { required: true, message: '请选择课程' },
      },
      {
        name: 'class_name',
        rules: { required: true, message: '请选择学习月份' },
      },
      {
        name: 'sex',
        rules: { required: true, message: '请选择性别' },
      },
      {
        name: 'name',
        rules: { required: true, message: '请填写姓名' },
      },
      {
        name: 'phone',
        rules: [{ required: true, message: '请填写手机号' }, { mobile: true, message: '手机号格式不对' }],
      },
      // {
      //   name: 'cityText',
      //   rules: { required: true, message: '请选择籍贯' },
      // },
      {
        name: 'provice',
        rules: { required: true, message: '请选择省份' },
      },
      {
        name: 'city',
        rules: { required: true, message: '请选择城市' },
      },
      {
        name: 'county',
        rules: { required: true, message: '请选择区县' },
      },
      {
        name: 'now_status',
        rules: { required: true, message: '请选择目前状况' },
      },
      {
        name: 'school',
        rules: { required: true, message: '请选择学校' },
      },
      {
        name: 'major',
        rules: { required: true, message: '请选择专业' },
      },
      {
        name: 'education',
        rules: { required: true, message: '请选择学历' },
      },
      {
        name: 'is_base',
        rules: { required: true, message: '请选择是否有基础' },
      },
      {
        name: 'other_name',
        rules: { required: true, message: '请填写紧急联系人姓名' },
      },
      {
        name: 'other_phone',
        rules: [{ required: true, message: '请填写紧急联系人电话' }, { mobile: true, message: '手机号格式不对' }]
      },
      {
        name: 'other_relation',
        rules: { required: true, message: '请填写与紧急联系人关系' },
      },
    ]
  },

   /**
   * 生命周期函数--监听页面加载
   */
  async onLoad() {
    wx.showLoading({ title: '正在加载', mask: true })
    try {
      const studentInfo = app.globalData.studentInfo
      if(studentInfo) {
        this.setData({ 
         "student.type": studentInfo.class.class_type,
         "student.name": studentInfo.name, // 姓名
         "student.sex": studentInfo.sex,  // 1男 2女
         "student.phone": studentInfo.phone, // 电话
         "student.class_id": studentInfo.class_id, // 班级id,
         "student.class_name": studentInfo.class.class_name, // 班级名称,
         "student.wx_openid": studentInfo.wx_openid,
         "student.wx_nickname": studentInfo.wx_nickname,
         "student.wx_avatar": studentInfo.wx_avatar,
         "student.provice": studentInfo.provice, // 省
         "student.city": studentInfo.city, //  市
         "student.county": studentInfo.county, // 县
         "student.now_status": studentInfo.now_status, // 1:应届，2：在校，3：转行,
         "student.pre_career": studentInfo.pre_career, // 前职业
         "student.school": studentInfo.school, // 学校
         "student.major": studentInfo.major, // 专业
         "student.education": studentInfo.education, // 学历
         "student.is_base": studentInfo.is_base, // 是否有基础:1:有,2:没有
         "student.other_name": studentInfo.other_name, // 紧急联系人
         "student.other_phone": studentInfo.other_phone, // 紧急联系人电话
         "student.other_relation": studentInfo.other_relation, // 紧急联系人关系
         "student.source": studentInfo.source, // 紧急联系人关系
         "student.remarks": studentInfo.remarks, // 备注
        })
      }
      await this.getClassList()
    } catch(e) {
      console.log(e)
    }
    wx.hideLoading()
  },
  async getClassList() {
    const { data } = await fetchClassList()
    const dateUI = []
    const dateH5 = []
    data.map(item=> {
      if(item.class_type === 1) {
        dateUI.push(item)
      }else if(item.class_type === 2) {
        dateH5.push(item)
      }
    })
    this.setData({
      dateUI,
      dateH5
    })
  },
  
  selectType(e) {
    if(e.currentTarget.dataset.type == '1') {
      const { id, class_name } = this.data.dateUI[0]
      this.setData({
        "student.type": e.currentTarget.dataset.type,
        "student.class_id": id,
        "student.class_name": class_name
      })
    }else {
      const { id, class_name } = this.data.dateH5[0]
      this.setData({
        "student.type": e.currentTarget.dataset.type,
        "student.class_id": id,
        "student.class_name": class_name
      })
    }
  },
  dateChangeUI(e) {
    const { id, class_name } = this.data.dateUI[e.detail.value]
    this.setData({
      "student.class_id": id,
      "student.class_name": class_name
    })
  },
  dateChangeH5(e) {
    const { id, class_name } = this.data.dateH5[e.detail.value]
    this.setData({
      "student.class_id": id,
      "student.class_name": class_name
    })
  },
  
  sexChange:function(e){
    this.setData({
      "student.sex": e.detail.value
    })
  },
  userChange:function(e){
    this.setData({
      "student.name":e.detail.value
    })
  },
  telChange: function(e){
    this.setData({
      "student.phone": e.detail.value
    })
  },
  cityChange:function(e){
    const [ provice, city, county ] = e.detail.value
    this.setData({
      "student.provice": provice,
      "student.city": city,
      "student.county": county
    })
  },
  statusChange:function(e){
    // 当前状态
    this.setData({
      "student.now_status": e.detail.value
    })
  },
  sourceChange:function(e){
    // 来源
    this.setData({
      "student.source": e.detail.value
    })
  },
  schoolChange:function(e){
    this.setData({
      'student.school':e.detail.value
    })
  },
  majorChange: function (e) {
    this.setData({
      'student.major': e.detail.value
    })
  },
  eduChange: function (e) {
    this.setData({
      'student.education': e.target.dataset.type
    })
  },
  careerChange: function (e) {
    this.setData({
      'student.pre_career': e.detail.value
    })
  },
  expChange: function (e) {
    // console.log(e.detail);
    this.setData({
      "student.is_base": e.detail.value
    })
  },
  secondNameChange:function(e){
    this.setData({
      "student.other_name": e.detail.value
    })
  },
  secondTelChange: function (e) {
    this.setData({
      "student.other_phone": e.detail.value
    })
  },
  secondInterChange: function (e) {
    this.setData({
      "student.other_relation": e.detail.value
    })
  },
  remarksChange: function (e) {
    this.setData({
      "student.remarks": e.detail.value
    })
  },
  agreeChange:function(e){
    this.setData({
      "student.isAgree":e.detail.value.length?true:false
    })
  },
  toInfo:function(){
    if (this.data.student.type && this.data.student.class_name){
      this.setData({
        isActive: 'info'
      })
    }else {
      wx.showToast({ title: '请先选择课程和班级', icon: 'none', mask: true })
    }
    
    // this.animate('.course-form', [
    //   { translateX:'-25%' }
    // ], 1000)
  },
  toCourse: function (e) {
    this.setData({
      isActive:'course'
    })
  },
  getUserInfo(e) {
    if(e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      wx.setStorageSync("userInfo", e.detail.userInfo)
      const { nickName, avatarUrl } = e.detail.userInfo
      this.setData({
        "student.wx_openid": wx.getStorageSync('openid'),
        "student.wx_nickname": nickName,
        "student.wx_avatar": avatarUrl,
      })
      this.submit()
    }else {
      // 用户不同意
      wx.showToast({
        title: '请同意后再提交数据',
        icon:"none"
      })
    }
  },
  submit(){
    // console.log(this.data.student)
    // 校验数据
    this.selectComponent('#form').validate((valid, errors) => {
      console.log('valid', valid, errors)
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          wx.showToast({
            title: errors[firstError[0]].message,
            icon:"none"
          })
        }
      } else {
        wx.showLoading({ title: '正在提交数据', mask: true })
        const { student } = this.data
        
        fetchEnter(student)
          .then(res => {
            wx.hideLoading()
            wx.redirectTo({
              url: '../finish/index',
            })
          })
          .catch(err=> {
            wx.hideLoading()
          }) 
      }
    })
  },
 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    const res = wx.getSystemInfoSync();
    // console.log(res)
    this.setData({
      height: res.windowHeight
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    wx.showLoading({ title: '正在加载', mask: true })
    try {
      await this.getClassList()
      wx.showToast({ title: '班级列表已更新', icon: 'none', mask: true })
    }catch(e) {
    }
    wx.hideLoading()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})